<template>
  <div class="login_container">
    <div class="login_box">
      <!--头像区-->
      <div class="avatar_box">
        <img src="../assets/logo.png" alt="" />
      </div>
      <!--登录表单区域-->
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        label-width="0px"
        class="login_form"
      >
        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input
            ref="userNameRef"
            v-model="loginForm.username"
            prefix-icon="iconfont icon-users"
            @focus="$utils.focus($event)"
          ></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            prefix-icon="iconfont icon-3702mima"
            @focus="$utils.focus($event)"
          ></el-input>
        </el-form-item>
        <!-- 按钮区域 -->
        <el-form-item>
          <el-row class="btns">
            <el-button type="primary" @click="login">登录</el-button>
            <el-button type="info" @click="resetLoginForm">重置</el-button>
          </el-row>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { postLogin } from "network/user.js";
export default {
  name: "Login",
  data() {
    return {
      loginForm: {
        username: "",
        password: ""
      },
      redirect: "",
      //表单验证规则
      loginRules: {
        //验证用户名是否合法
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        //验证密码是否合法
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 3, max: 15, message: "长度在 3 到 15 个字符", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getRedirectUrl();
  },
  mounted() {
    this.$refs.userNameRef.focus();
  },
  activated() {
    this.getRedirectUrl();
  },
  methods: {
    //重置按钮,点击重置表单
    resetLoginForm() {
      this.$refs.loginFormRef.resetFields();
    },
    //登录
    login() {
      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) return;
        //登录不能使用get,会暴露帐号密码    const { data: res } 从返回体中结构处data,并重命名为res
        // const { data: res } = await this.$http.post("user", this.loginForm);

        // postLogin(this.loginForm).then(res=>{})
        try {
          const data = await postLogin(this.loginForm);
          if (!data) return;
          if (!data.success) return this.$message.error({ showClose: true, message: data.msg });
          this.$message.success({ showClose: true, message: data.msg });
          //1.将登陆成功的token,保存到客户端sessionStorage中
          //1.1项目中除了登录之外的其它接口,必须在登陆之后才能访问
          //1.2token只应在页面打开时生效,所以将token保存在sessionStorage中
          window.sessionStorage.setItem(
            "token",
            data.response.tokenType + " " + data.response.token
          );
          // window.sessionStorage.token = data.response.token;//一样的写法
          // console.log(window.sessionStorage.token);
          //存储过期时间
          var curTime = new Date();
          var expiration = new Date(
            curTime.setSeconds(curTime.getSeconds() + data.response.expiration)
          );
          window.sessionStorage.setItem("tokenExpire", expiration);
          window.sessionStorage.refreshTime = expiration;
          //2.通过编程式导航跳转到后台主页,路由地址是redirect或/home
          if (this.redirect) return this.$router.push(this.redirect);
          return this.$router.push("/home");
        } catch (error) {
          console.log(error.message);

          this.$message.error({ showClose: true, message: "网络异常" });
        }
      });
    },
    getRedirectUrl() {
      //从url中获取重定向的参数
      this.redirect = this.$route.query.redirect;
      let token = window.sessionStorage.getItem("token");
      // console.log(token);
      // console.log(this.redirect);
      // console.log(!token);
      if (this.redirect && !token)
        //放置节流函数, 避免重复弹窗;
        return this.$message.error({
          showClose: true,
          message: "登录状态过期,请重新登录"
        });
    }
  }
};
</script>

<style lang="less" scoped>
.login_container {
  background-color: #2b4b6b;
  height: 100%;
}
.login_box {
  width: 450px;
  height: 300px;
  background-color: #fff;
  border-radius: 3px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%); //位移:横轴移动-50%,纵轴移动-50%
  //less的语法嵌套
  .avatar_box {
    height: 130px;
    width: 130px;
    border: 1px solid #eee;
    border-radius: 50%;
    padding: 10px;
    box-shadow: 0 0 10px #eee;
    position: absolute;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;
    img {
      height: 100%;
      width: 100%;
      border-radius: 50%;
      background-color: #eee;
    }
  }
}
.btns {
  display: flex;
  justify-content: flex-end;
}
.login_form {
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
}
</style>
